package com.leyou.mall.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leyou.mall.data.entity.Brand;
import com.leyou.mall.data.entity.Files;
import com.leyou.mall.data.entity.Result;
import com.leyou.mall.data.vo.BrandVo;
import com.leyou.mall.mapper.FileMapper;
import com.leyou.mall.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;


/**
 * @author 车矣捕
 * @version 1.0
 * @description: 描述
 * @date 2022/5/29 19:45
 */
@RestController
@RequestMapping("/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    @Autowired
    private FileMapper fileMapper;

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @PostMapping("/brandList")
    public Result brandList(BrandVo vo){
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        long pageNum=vo.getPageNum();
        long pageSize= vo.getPageSize();
        if (!"".equals(vo.getBrandName())){
            queryWrapper.like("brand_name",vo.getBrandName()).or().like("number",vo.getBrandName());
        }

        return Result.success(brandService.page(new Page<>(pageNum, pageSize),queryWrapper));
    }

    /** @description: 文件上传接口  */
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        System.out.println("文件上传接口");
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        // 定义一个文件唯一的标识码
        String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type;

        File uploadFile = new File(fileUploadPath + fileUUID);
        // 判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        File parentFile = uploadFile.getParentFile();
        if(!parentFile.exists()) {
            parentFile.mkdirs();
        }

        String url;
        // 获取文件的md5
        String md5 = SecureUtil.md5(file.getInputStream());
        // 从数据库查询是否存在相同的记录
        Files dbFiles = getFileByMd5(md5);
        if (dbFiles != null) {
            url = dbFiles.getUrl();
        } else {
            // 上传文件到磁盘
            file.transferTo(uploadFile);
            // 数据库若不存在重复文件，则不删除刚才上传的文件
            url = "http://localhost:9000/api/management-mall/brand/" + fileUUID;
        }


        // 存储数据库
        Files saveFile = new Files();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024); // 单位 kb
        saveFile.setUrl(url);
        saveFile.setMd5(md5);
        fileMapper.insert(saveFile);

        return url;
    }

    /** 通过文件的md5查询文件 */
    private Files getFileByMd5(String md5) {
        // 查询文件的md5是否存在
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        List<Files> filesList = fileMapper.selectList(queryWrapper);
        return filesList.size() == 0 ? null : filesList.get(0);
    }

    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }


    /*** @description:  上/下 架 */
    @PostMapping("/updateStatus")
    public Result updateStatus( BrandVo vo) {
        Brand brand = new Brand();
        brand.setId(vo.getId());
        brand.setStatus(vo.getStatus());
        System.out.println("上/下 架:--"+brand);
        return Result.success(brandService.updateById(brand));
    }
}
